Page({
  data: {
    title: '',
    categoryList: ['住院陪护', '院外陪护', '社会化转运', '陪检'],
    categoryValue: '',
    gender: '0',
    chargeType: '0',
    address: '',
    intro: '',
    startTime: '',
    endTime: '',
    today: '',
    totalAmount: 0,
    amountDesc: '请选择计费方式和时间计算金额'
  },

  onLoad() {
    const now = new Date();
    const todayStr = `${now.getFullYear()}-${this.formatNum(now.getMonth() + 1)}-${this.formatNum(now.getDate())}`;
    this.setData({ 
      today: todayStr,
      totalAmount: 0
    });
    console.log('页面加载完成，today:', todayStr);
  },

  formatNum(num) {
    return num < 10 ? `0${num}` : num;
  },

  bindTitleInput(e) {
    this.setData({ title: e.detail.value });
  },

  bindCategoryChange(e) {
    const index = e.detail.value;
    this.setData({ categoryValue: this.data.categoryList[index] });
  },

  bindGenderChange(e) {
    this.setData({ gender: e.detail.value });
  },

  bindChargeChange(e) {
    const chargeType = e.detail.value;
    this.setData({ chargeType }, () => {
      this.calculateAmount();
    });
  },

  bindAddressInput(e) {
    this.setData({ address: e.detail.value });
  },

  bindIntroInput(e) {
    this.setData({ intro: e.detail.value });
  },

  bindStartTimeChange(e) {
    const startTime = e.detail.value;
    if (this.data.endTime && this.data.endTime < startTime) {
      this.setData({ endTime: '' });
    }
    this.setData({ startTime }, () => {
      this.calculateAmount();
    });
  },

  bindEndTimeChange(e) {
    const endTime = e.detail.value;
    this.setData({ endTime }, () => {
      setTimeout(() => {
        this.calculateAmount();
      }, 100);
    });
  },

  calculateAmount() {
    const { startTime, endTime, chargeType } = this.data;
    
    console.log('=== 开始计算金额 ===');
    console.log('关键数据：', { startTime, endTime, chargeType });

    const priceConfig = {
      fullDay: 200,    
      perHour: 25,     
      dayHour: 8       
    };

    if (!chargeType) {
      console.log('未选择计费方式');
      this.setData({ 
        totalAmount: 0, 
        amountDesc: '请选择计费方式' 
      });
      return;
    }

    if (!startTime || !endTime) {
      console.log('未选择完整陪护日期');
      this.setData({ 
        totalAmount: 0, 
        amountDesc: '请选择完整陪护日期' 
      });
      return;
    }

    const startMs = new Date(startTime).getTime();
    const endMs = new Date(endTime).getTime();
    
    if (isNaN(startMs) || isNaN(endMs)) {
      console.log('日期格式错误');
      this.setData({ 
        totalAmount: 0, 
        amountDesc: '日期格式错误' 
      });
      return;
    }

    const dayDiff = Math.ceil((endMs - startMs) / (24 * 60 * 60 * 1000)) + 1;
    console.log('计算出的天数：', dayDiff);

    let totalAmount = 0;
    let amountDesc = '';
    
    if (chargeType === '0') {
      totalAmount = dayDiff * priceConfig.fullDay;
      amountDesc = `${dayDiff}天 × ${priceConfig.fullDay}元/天 = ${totalAmount}元`;
    } else {
      const totalHour = dayDiff * priceConfig.dayHour;
      totalAmount = totalHour * priceConfig.perHour;
      amountDesc = `${dayDiff}天 × ${priceConfig.dayHour}小时/天 × ${priceConfig.perHour}元/小时 = ${totalAmount}元`;
    }

    console.log('计算结果：', { totalAmount, amountDesc });

    this.setData({
      totalAmount: totalAmount,
      amountDesc: amountDesc
    }, () => {
      console.log('数据更新完成：', this.data.totalAmount, this.data.amountDesc);
    });
  },

  testAmountDisplay() {
    console.log('=== 手动测试金额显示 ===');
    console.log('当前数据状态:', this.data);
    
    this.setData({
      startTime: '2025-10-15',
      endTime: '2025-10-16',
      chargeType: '0',
      totalAmount: 400,
      amountDesc: '2天 × 200元/天 = 400元'
    }, () => {
      console.log('手动设置完成，数据状态:', this.data);
      wx.showToast({
        title: '测试设置完成',
        icon: 'success'
      });
    });
  },

  submitForm() {
    this.calculateAmount();
    
    const { title, categoryValue, address, startTime, endTime, totalAmount, chargeType, gender, intro, amountDesc } = this.data;
  
    // 基础验证
    if (!title) { 
      wx.showToast({ title: '请输入标题', icon: 'none' }); return; 
    }
    if (!categoryValue) { 
      wx.showToast({ title: '请选择类别', icon: 'none' }); return; 
    }
    if (!address) { 
      wx.showToast({ title: '请输入地址', icon: 'none' }); return; 
    }
    if (!startTime || !endTime) { 
      wx.showToast({ title: '请选择陪护日期', icon: 'none' }); return; 
    }
    if (totalAmount <= 0) { 
      wx.showToast({ title: '金额异常，请重新选择', icon: 'none' }); return; 
    }
  
    const formData = {
      title,
      categoryValue,
      gender: gender === '0' ? '不限' : gender === '1' ? '男' : '女',
      chargeType: chargeType === '0' ? '全天（200元/天）' : '按小时（25元/小时）',
      address,
      intro: intro || '无',
      startTime,
      endTime,
      totalAmount,
      amountDesc: amountDesc || '请选择计费方式和时间计算金额'
    };
    
    wx.setStorageSync('formData', formData);
    wx.navigateTo({
      url: '/pages/pay/pay' 
    });
  }
});